<?php

namespace App\Http\Controllers;

use App\Http\Resources\OperationLogResource;
use App\Http\Traits\CheckPermission;
use App\Models\OperationLog;
use App\Models\Permission;
use App\Services\OperationLogService;
use Illuminate\Http\Request;

class OperationLogController extends Controller
{
    use CheckPermission;

    protected $logService;
    protected $resource = 'operation_logs';

    public function __construct(OperationLogService $logService)
    {
        $this->logService = $logService;
        $this->middleware('auth.api');
    }

    public function index(Request $request)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $filters = $request->only([
            'username',
            'path',
            'status',
            'action',
            'resource',
            'resource_id',
            'description',
            'start_time',
            'end_time'
        ]);
        $query = $this->logService->buildQuery($filters);
        $logs = $query->paginate($this->getPageSize($request));

        // 使用Resource格式化分页数据，包括时间字段
        // 将Resource对象转换为数组，确保时间格式正确
        $logs->setCollection(
            $logs->getCollection()->map(function ($log) {
                return (new OperationLogResource($log))->resolve(request());
            })
        );

        return $this->success($logs, '获取成功');
    }

    public function show($id)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $log = OperationLog::with('user')->findOrFail($id);
        return $this->success(new OperationLogResource($log), '获取成功');
    }

    public function destroy($id)
    {
        // 检查删除权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_DELETE);

        $log = OperationLog::findOrFail($id);
        $log->delete();
        return $this->success(null, '删除成功');
    }

    public function clear()
    {
        // 检查删除权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_DELETE);

        if ($this->logService->clearAll()) {
            return $this->success(null, '清空成功');
        }
        
        return $this->error('清空失败', 500);
    }
}

